<template>
  <a-spin :spinning="confirmLoading" style="margin-top: 0px;margin-bottom: 0px">
    <j-form-container :disabled="formDisabled" >
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-card title="当前状态" :bordered="false" >
          <a-row type="flex" justify="start">
            <a-col :span="12" >
              <tsl-step :list="steplist" :currentStatus="model.stepStatus"></tsl-step>
            </a-col>
          </a-row>
        </a-card>
        <a-divider style="margin: 5px 0px;"/>
        <a-row>
          <a-col :span="6" >
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input disabled v-model="model.code" placeholder="请输入单据编号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="入库类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="storageType">
              <j-dict-select-tag style="width: 200px" :disabled="isProcStorage" type="list" v-model="model.storageType"
                                 dictCode="rk_type" placeholder="请选择入库类型" :disabledVal="3"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="生产车间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="workshop">
              <j-dict-select-tag style="width: 200px"  type="list" v-model="model.workshop"
                                 dictCode="erp_production_workshop,name,id" placeholder="请选择生产车间" @change="changeWorkShop"/>
            </a-form-model-item>
          </a-col>
<!--          <a-col :span="6" >-->
<!--            <a-form-model-item label="供应商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="venderId">-->
<!--              <tsl-supplier v-model="model.supplierId" @handlerOk="noticeSupplierOk" :isDisabled="isProcStorage"> </tsl-supplier>-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
        </a-row>
        <a-row v-show="!isProcStorage">
          <a-col :span="6" >
            <a-form-model-item label="宝洁供应商编码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bjSupplierCode">
              <a-input v-model="model.bjSupplierCode"  placeholder="宝洁供应商编码" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="宝洁采购订单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bjProcurementCode">
              <a-input v-model="model.bjProcurementCode"  placeholder="宝洁采购订单号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="宝洁供应商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bjSupplierName">
              <a-input v-model="model.bjSupplierName"  placeholder="宝洁供应商" ></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <a-tabs
            :default-active-key="tabkeys[0]"
            >
      <a-tab-pane tab="入库信息" :key="tabkeys[0]"  :forceRender="true">
        <a-card title="收货信息" :bordered='false'>
          <j-vxe-table
             keep-source
            :ref="refKeys[0]"
            :loading="bussStorageNoticeMaterialTable.loading"
            :columns="bussStorageNoticeMaterialTable.columns"
            :dataSource="bussStorageNoticeMaterialTable.dataSource"
            :maxHeight="300"
            :disabled="formDisabled"
            :rowNumber="true"
            :rowSelection="true"
            :toolbar="true"
            :toolbarConfig="{slot: ['prefix', 'suffix'], btn: ['clearSelection']}"
            class="bold-border"
             @edit-closed="editMaterialClosedEvent"
             :clickSelectRow="true"
             rowSelectionType="radio"
          >
            <template    v-slot:toolbarSuffix>
<!--              <a-button @click='addMaterial' v-if='!procurementShow && model.type'>新增</a-button>-->
              <a-button @click='addMaterialInfo' v-show="!bussinessDisable && !formDisabled">新增</a-button>
<!--              <a-button @click='addMaterial' >新增</a-button>-->
<!--              <a-button @click='editMaterial' >编辑</a-button>-->
              <a-button @click='deleteMaterial' v-show="!formDisabled">删除</a-button>
              <a-button @click='handleCK' v-show="!formDisabled">添加车辆信息</a-button>
              <a-button @click='clearCheck("materical")' v-show="!formDisabled">清空选择</a-button>
            </template>
            <template v-slot:erpLocationName="props">
              <tsl-warehouse v-model="props.value" :disabled="formDisabled" :rowData='props' @handlerOk="warehouseOk"></tsl-warehouse>
            </template>
            <template v-slot:supplierId="props">
              <tsl-mat-supplier v-model="props.value" :isDisabled="bussinessDisable && !formDisabled" :rowData='props'
                                @handlerOk="supplierOk"></tsl-mat-supplier>
            </template>

          </j-vxe-table>
        </a-card>
        <a-card title="车辆信息" :bordered='false'>
          <j-vxe-table
            keep-source
            :ref="refKeys[1]"
            :loading="bussStorageNoticeCarinfoTable.loading"
            :columns="bussStorageNoticeCarinfoTable.columns"
            :dataSource="bussStorageNoticeCarinfoTable.dataSource"
            :maxHeight="300"
            :disabled="formDisabled"
            :rowNumber="true"
            :rowSelection="true"
            :toolbar="true"
            :autoResize="true"
            :toolbarConfig="{slot: ['prefix', 'suffix'], btn: ['clearSelection']}"
            @edit-closed="editClosedEvent"
            :clickSelectRow="true"
          >
            <template    v-slot:toolbarSuffix>
              <a-button @click='deleteCarinfo' v-show="!formDisabled">删除</a-button>
              <a-button @click='clearCheck("car")' v-show="!formDisabled">清空选择</a-button>
            </template>
          </j-vxe-table>
        </a-card>
      </a-tab-pane>
      <a-tab-pane tab="状态履历修改" :key="tabkeys[1]"  :forceRender="true">
        <a-card :bordered='false'>
          <tsl-history  dataTable="buss_storage_notice"  :dataId="model.id"></tsl-history>
        </a-card>
      </a-tab-pane>
    </a-tabs>

    <!-- 采购单 -->
<!--    <buss-material-procurement-list-->
<!--                ref='procurement' @handleOk='procurementOk' :procurementType='procurementType' checkval='checkbox'></buss-material-procurement-list>-->
    <erp-supplier-list ref='supplier' @handlerOk='supplierOk'> </erp-supplier-list>
    <erp-good-list ref='good'
                   @handlerOk='goodOk'
                   checkval='checkbox'
                   :supplierId="model.supplierId"></erp-good-list>
  </a-spin>
</template>
<script>
import { getAction, postAction } from '@/api/manage'
  import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
  import { JVXETypes } from '@/components/jeecg/JVxeTable'
  import { getRefPromise,VALIDATE_FAILED} from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import BussMaterialProcurementList  from '@/views/modules/procurement/BussMaterialProcurementList'
  import ErpSupplierList from '@/views/modules/supplier/ErpSupplierList'
  import ErpGoodList from '@/views/modules/goods/ErpGoodsListModal'
  import ErpLocationList from '@/views/modules/location/ErpLocationList'
  import DetailsModal from '@/components/modal/DetailsModal'
  import TslStep from '@/components/tsl/TslStep'

  import moment from 'dayjs'
  import TslWarehouse from '@comp/tsl/TslWarehouse.vue'
  import TslMatSupplier from '@comp/tsl/cell/TslMatSupplier.vue'
  import TslHistory from '@comp/tsl/TslHistory.vue'
  import TslSupplier from '@comp/tsl/TslSupplier.vue'
  import '@/assets/less/tsl_common.less'

  export default {
    name: 'BussStorageNoticeForm',
    mixins: [JVxeTableModelMixin],
    components: {
      JFormContainer,BussMaterialProcurementList,ErpSupplierList,ErpGoodList,ErpLocationList,
      DetailsModal,TslStep,TslWarehouse,TslMatSupplier,TslHistory,TslSupplier
    },
    data() {
      const actualNum = (rule, value, callback) => {
        callback(new Error('请再次输入密码'));
        // if (value === '') {
        //   callback(new Error('请再次输入密码'));
        // } else if (value !== this.formInfo.password) {
        //   callback(new Error('两次密码不同'));
        // } else {
        //   callback();
        // }
      };
      return {
        // bussinessDisable: false,
        procSelectRows: [],
        toolBtn: [ 'remove', 'clearSelection'],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        model:{
          stepStatus: 0,
          storageType: null
         },
        steplist:[
          {title:'草稿'},{title:'采购确认'},{title:'入库'}
        ],
        rules: {
          // num: [
          //   {required: true, message: '必须输入序号'},
          // ],
          // erpLocationId: [
          //   { required: true, message: '请选择库位' },
          // ]
        },
        noticeMaterialRowNum: 0,
        carRowNum: 0,
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 0,
        validatorRules: {
          erpLocationId: [{required: true, message: '请选择库位'}],
        },
        historyOption: [],
        refKeys: ['bussStorageNoticeMaterial', 'bussStorageNoticeCarinfo', ],
        tableKeys:['bussStorageNoticeMaterial', 'bussStorageNoticeCarinfo', ],
        tabkeys: ['material','uphistorys'],
        activeKey: 'material',
        // 入库通知单原料单
        bussStorageNoticeMaterialTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '行项目',
              key: 'rowNum',
              type: JVXETypes.normal,
              width:"70px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '物料编号',
              key: 'materialCode',
              type: JVXETypes.normal,
              width: '150px',
            },
            {
              title: '物料名称',
              key: 'materialName',
              type: JVXETypes.normal,
              width: '150px',
            },
            {
              title: '规格',
              key: 'spec',
              type: JVXETypes.normal,
              width: '70px',
            },
            {
              title: '库位名称',
              key: 'erpLocationId',
              type: JVXETypes.slot,
              slotName: 'erpLocationName',
              width: '200px',
              validateRules: [{ required: true, message: '请选择${title}' }]
            },
            {
              title: '原发数量',
              key: 'originalNum',
              type: JVXETypes.normal,
              width:"120px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '实收数量',
              key: 'actualNum',
              type: JVXETypes.normal,
              width:"120px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '批次号',
              key: 'batchNum',
              type: JVXETypes.input,
              width: '120px',
              validateRules: [
                {
                  handler({ cellValue, row, column }, callback, target) {
                    if(cellValue && cellValue.length > 10){
                      callback(false, '${title}不能大于10位')  // false = 未通过校验
                    }else if(cellValue){
                      callback(true) // true = 通过验证
                    }
                    callback(false)
                  },
                  message: '请输入${title}',
                  required: true
                },
              ],
              // validateRules: [{ required: true, message: '请输入${title}' }]
            },
            {
              title: '物料批号',
              key: 'materialLotNum',
              type: JVXETypes.input,
              width: '120px',
              validateRules: [
                {
                  handler({ cellValue, row, column }, callback, target) {
                    if(cellValue && cellValue.length > 10){
                      callback(false, '${title}不能大于10位')  // false = 未通过校验
                    }
                    callback(true)
                  },
                  message: '请输入${title}',
                  required: false
                }
              ],
            },
            {
              title: '客户物料编号',
              key: 'customerMaterialNo',
              type: JVXETypes.input,
              width:"120px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '入库日期',
              key: 'warehouseDate',
              type: JVXETypes.date,
              width:"120px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '生产日期',
              key: 'createDate',
              type: JVXETypes.date,
              width:"120px",
              placeholder: '请输入${title}',
            },
            {
              title: '限用日期',
              key: 'expiryDate',
              type: JVXETypes.date,
              width:"120px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '排产单号',
              key: 'schedulingCode',
              type: JVXETypes.input,
              width: '120px',
              validateRules: [
                {
                  handler({ cellValue, row, column }, callback, target) {
                    if(cellValue && cellValue.length > 10){
                      callback(false, '${title}不能大于10位')  // false = 未通过校验
                    }
                    callback(true)
                  },
                  message: '请输入${title}',
                  required: false
                },
              ],
            },
            {
              title: '生产车间',
              key: 'workshop',
              type: JVXETypes.select,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
              dictCode: 'erp_production_workshop,name,id',
              disabled: true
            },
            {
              title: '采购数量',
              key: 'procurementNum',
              type: JVXETypes.normal,
              width: '120px',
            },
            {
              title: '已到货数量',
              key: 'arrivalNum',
              type: JVXETypes.normal,
              width: '70px',
            },
            {
              title: '单位',
              key: 'meUnit',
              type: JVXETypes.selectSearch,
              width: '70px',
              dictCode: 'ji_unit',
              // disabled: true
            },
            {
              title: '供应商',
              key: 'supplierId',
              type: JVXETypes.slot,
              width: '200px',
              slotName: 'supplierId',
            },
            {
              title: '采购订单编号',
              key: 'procurementCode',
              type: JVXETypes.normal,
              width: '120px',
            },
            {
              title: '采购明细id',
              key: 'procurementDetailId',
              type: JVXETypes.hidden,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '原料id',
              key: 'materialId',
              type: JVXETypes.hidden,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '辅助数量',
              key: 'supportNum',
              type: JVXETypes.hidden,
              width: '120px',
            },
            {
              title: '辅助单位',
              key: 'supportUnit',
              type: JVXETypes.hidden,
              width: '70px',
            },
            {
              title: '当前状态',
              key: 'status',
              type: JVXETypes.hidden,
              width:"70px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
          ]
        },
        // 入库通知单-车辆信息
        bussStorageNoticeCarinfoTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: 'id',
              key: 'id',
              type: JVXETypes.hidden,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '行项目',
              key: 'rowNum',
              type: JVXETypes.normal,
              width:"70px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '通知单id',
              key: 'noticeId',
              type: JVXETypes.hidden,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '车牌号',
              key: 'carNum',
              type: JVXETypes.input,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [
                {
                  handler({ cellValue, row, column }, callback, target) {
                    if(cellValue && cellValue.length > 10){
                      callback(false, '${title}不能大于10位')  // false = 未通过校验
                    }
                    callback(true)
                  },
                  message: '请输入${title}',
                  required: false
                },
              ],
            },
            {
              title: '物料编号',
              key: 'materialCode',
              type: JVXETypes.normal,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '物料名称',
              key: 'materialName',
              type: JVXETypes.normal,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '单位',
              key: 'meUnit',
              type: JVXETypes.select,
              width: '150px',
              dictCode: 'ji_unit',
              disabled: true
            },
            {
              title: '原发数',
              key: 'originalNum',
              type: JVXETypes.inputNumber,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '实际数量',
              key: 'actualNum',
              type: JVXETypes.inputNumber,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '备注',
              key: 'remark',
               type: JVXETypes.input,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            // {
            //   title: '操作',
            //   key: 'action',
            //   type: JVXETypes.slot,
            //   fixed: 'right',
            //   minWidth: '200px',
            //   align: 'center',
            //   slotName: 'action',
            // }
          ]
        },
        NoticeMaterialTable: '',
        CarTableRef: '',
        isProcStorage: false,
        url: {
          add: "/business/bussStorageNotice/add",
          edit: "/business/bussStorageNotice/edit",
          queryById: "/business/bussStorageNotice/queryById",
          bussStorageNoticeCarinfo: {
            list: '/business/bussStorageNotice/queryBussStorageNoticeCarinfoByMainId'
          },
          bussStorageNoticeMaterial: {
            list: '/business/bussStorageNotice/queryBussStorageNoticeMaterialByMainId'
          },
        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      /*流程自定义表单数据*/
      customFormData:{
        type:Object,
        default:()=>{return {}},
        required:false
      },
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
      procurementShow: {
        get(){
          if(typeof this.model.type === 'undefined'){
            return false
          }
          if((this.model.type == 0 || this.model.type == 1) && (this.model.arrayType)){
            return false
          }
          return this.model.type == 0 || this.model.type == 1
        },
        set(){}
      },
      bussinessDisable(){
        if(this.model.storageType  && this.model.storageType == 3){
          return true;
        }
        return false;
      }
    },
    created () {


    },
    mounted() {
      this.$nextTick(() => {
        this.getAllTable().then(tables=>{
          this.NoticeMaterialTable = tables[0]
          this.CarTableRef = tables[1]
        })
        setTimeout(() => {
          if(!this.model.id){
            let rows = this.NoticeMaterialTable.getNewDataWithId()
            this.NoticeMaterialTable.removeRowsById(rows[0].id)
            let rows_car = this.CarTableRef.getNewDataWithId()
            this.CarTableRef.removeRowsById(rows_car[0].id)
            this.NoticeMaterialTable.syncHeaderScroll = true;
            this.CarTableRef.syncHeaderScroll = true;
          }
          this.scrollTop()
        },500)
      })
    },
    methods: {
      changeWorkShop(val){
        this.bussStorageNoticeMaterialTable.dataSource.forEach(item=>{
            item.workshop = val
        })
      },
      warehouseOk({result,row}){
        this.bussStorageNoticeMaterialTable.dataSource.forEach(item=>{
            if(item.materialId == row.materialId && item.rowNum == row.rowNum){
              item.erpLocationId = result.id
              item.erpLocationName = result.name
              item.erpLocationCode = result.code
              item.erpWarehouseName = result.warehouseName
              item.erpWarehouseCode = result.warehouseCode
            }
        })
        this.scrollTop()
      },
      editMaterialClosedEvent({ row, column }){
        let xTable = this.$refs.bussStorageNoticeMaterial
        let field = column.property
        let cellValue = row[field]
        let _this = this
        // 判断单元格值是否被修改
        this.$nextTick(() => {
          if('batchNum' === field){
            // if (xTable.isUpdateByRow(row, field)) {  // 判断值是否修改，但是不准确，有时会判断错误
              this.bussStorageNoticeMaterialTable.dataSource.forEach(mater => {
                if(mater.materialId == row.materialId){
                  mater.batchNum = cellValue
                }
              })
            // }
          }else if('createDate' === field || 'expiryDate' === field ){
            // if (xTable.isUpdateByRow(row, field)) {
              if(typeof row.createDate !== "undefined" && typeof row.expiryDate !== "undefined"){
                const date1 = moment(row.createDate);
                const date2 = moment(row.expiryDate);
                //updateNoticeMaterial
                let num = date2.diff(date1,'days');
                if(num < 0){
                  _this.$message.warn('限用日期小于生产日期!')
                  this.updateNoticeMaterial(row.rowNum,'expiryDate','');
                }else if(num < 30){
                 _this.$message.warn('限用日期是否输入正确!')
                }
              }
            // }
          }
        })
      },
      editClosedEvent ({ row, column }){
        // 车辆数量修改，物料数量跟着变动
        let xTable = this.$refs.bussStorageNoticeCarinfo
        let field = column.property
        let cellValue = row[field]
        // 判断单元格值是否被修改
        this.$nextTick(() => {
             if('actualNum' === field || 'originalNum' === field){
            // if (xTable.isUpdateByRow(row, field)) {
              let { rowNum, materialId, originalNum, actualNum } = row
              this.bussStorageNoticeMaterialTable.dataSource.forEach(mater => {
                // if('originalNum' === field){
                //   if(mater.materialId === materialId && mater.rowNum === rowNum){
                //     mater.originalNum = originalNum
                //     return;
                //   }
                // }
                if(mater.materialId === materialId && mater.rowNum === rowNum){
                  let actualNum = 0
                  let originalNum = 0
                  this.bussStorageNoticeCarinfoTable.dataSource.forEach(car =>{
                    if(car.rowNum === mater.rowNum && mater.materialId === car.materialId ){
                      actualNum +=  car.actualNum
                      originalNum += car.originalNum
                    }
                  })
                  if(this.model.storageType === 3){
                    let targetObj = Object.assign({},mater);
                    targetObj.originalNum = originalNum
                    targetObj.actualNum = actualNum
                    if(targetObj.id.indexOf('row')>=0){
                      targetObj.id = ''
                    }
                    postAction('/business/bussStorageNotice/checkProcMaterialNum',targetObj).then(res =>{
                      const {code,message} = res
                      if(code == 200){
                        mater.originalNum = originalNum
                        mater.actualNum = actualNum
                        this.NoticeMaterialTable.resetScrollTop();
                      }else {
                        this.$message.warn(message)
                      }
                    })
                  }else{
                    mater.originalNum = originalNum
                    mater.actualNum = actualNum
                  }
                }
              });
              this.NoticeMaterialTable.resetScrollTop();
            // }
          }
        })
      },
      edit(record) {
        if (typeof this.editBefore === 'function') this.editBefore(record)
        this.visible = true
        this.activeKey = this.refKeys[0]
        this.$refs.form.resetFields()
        this.model = Object.assign({}, record)
        if (typeof this.editAfter === 'function') this.editAfter(this.model)
      },
      addProc(){
        if(this.procSelectRows.length>0){
          const rows = this.procSelectRows
          //判断是否存在不同的供应商
          this.model.storageType = 3
          this.isProcStorage = true
          rows.forEach((item,index)=>{
            let detail = {}
            detail.rowNum = this.getRowNum()
            detail.procurementCode = item.code
            detail.procurementDetailId = item.id
            detail.warehouseDate = moment(new Date()).format('YYYY-MM-DD')
            detail.materialId = item.materialId
            detail.materialName = item.materialName
            detail.materialCode = item.materialCode
            detail.supplierId = item.supplierId
            detail.supplierCode = item.supplierCode
            detail.meUnit = item.meUnit
            detail.procurementNum = item.procurementNum
            detail.arrivalNum = item.arrivalNum
            this.bussStorageNoticeMaterialTable.dataSource.push(detail)
          })
        }
      },
      addMaterialInfo(){
        if(!this.model.storageType){
          this.$message.warn('请选择入库类型！')
          return;
        }
        if(this.model.storageType === 3){
          //采购
          this.onSearchProcurement()
        }else{
          //
          this.onSearchMaterial();
        }
      },
      deleteCarinfo(props){
        // 删除物料
        let rows =  this.CarTableRef.selectedRows;
        if(rows.length<=0){
          this.$message.warn('请选择车辆信息！')
          return;
        }
        rows.forEach(row=>{
          this.bussStorageNoticeCarinfoTable.dataSource = this.bussStorageNoticeCarinfoTable.dataSource.filter(item=>item.id !== row.id)
        })
      },
      handleCK(){
        // 添加车辆信息
        let rows =  this.NoticeMaterialTable.selectedRows;
        if(rows.length === 0 || rows.length > 1){
          this.$message.warn('请选择一个收货信息！')
          return;
        }
        rows.forEach(item=>{
          let detail = {
            actualNum: '',
            originalNum: '',
            rowNum: item.rowNum,
            materialId: item.materialId,
            materialCode: item.materialCode,
            materialName: item.materialName,
            meUnit: item.meUnit
          }
          this.bussStorageNoticeCarinfoTable.dataSource.push(detail)
        })
      },
      getPfCode() {
        if(this.model.id){
          return;
        }
        postAction('/sys/fillRule/executeRuleByCode/rktzd', {}).then(res => {
          this.model.code = res.result;
        })
      },
      deleteCarByMat(code,rowNum){
        // 删除车辆信息
        let data = this.bussStorageNoticeCarinfoTable.dataSource.filter(item=> item.materialCode !== code && item.rowNum !== rowNum)
        this.bussStorageNoticeCarinfoTable.dataSource =  data
      },
      goodOk(rows){
        let _this = this;
        rows.forEach((item,index)=>{
          let obj = {}
          obj.materialId= item.id
          obj.materialName= item.name
          obj.materialCode= item.code
          obj.spec= item.noneSpec
          obj.meUnit= item.meUnit
          obj.rowNum = this.getRowNum()
          obj.workshop = this.model.workshop
          obj.warehouseDate = moment(new Date()).format('YYYY-MM-DD')
          this.bussStorageNoticeMaterialTable.dataSource.push(obj)
        })
        this.scrollTop()
      },
      deleteMaterial(){
        // 删除物料
        let rows =  this.NoticeMaterialTable.selectedRows;
        if(rows.length<=0){
          this.$message.warn('请选择收货信息！')
          return;
        }
        rows.forEach(row=>{
          this.bussStorageNoticeMaterialTable.dataSource = this.bussStorageNoticeMaterialTable.dataSource.filter(item=>item.id !== row.id)
          this.deleteCarByMat(row.materialCode,row.rowNum);
        })
      },
      clearCheck(obj){
        if(obj == 'car'){
          this.CarTableRef.clearSelection();
        }else{
          this.NoticeMaterialTable.clearSelection();
        }
      },
      onSearchMaterial(){
        this.$nextTick(() => {
          this.$refs.good.add()
        })
      },
      supplierOk({row,value}){
        this.bussStorageNoticeMaterialTable.dataSource.forEach(item=>{
          if(item.materialId == row.materialId && item.rowNum == row.rowNum){
            item.supplierId = value
          }
        })
        this.scrollTop()
      },
      procurementOk({rows,callback}){
        //判断是否存在不同的供应商
        const supplierId = rows[0].supplierId
        const newrows = rows.filter(item=> item.supplierId === supplierId );
        if(newrows.length != rows.length){
          this.$message.warn('一个入库通知单单只能是同一个供应商！')
          return;
        }
        let jsonarray = rows.map(item=>({
          ...item,
          id: '',
          procurementCode: item.code,
          procurementDetailId: item.id,
          warehouseDate: moment(new Date()).format('YYYY-MM-DD'),
        }))
        this.bussStorageNoticeMaterialTable.dataSource.push(... jsonarray)
        callback(true)
      },
      onSearchProcurement(){
        // 采购订单
        this.$nextTick(() => {
          // this.$refs.procurement.add();
        })
      },
      addBefore(){
        this.bussStorageNoticeCarinfoTable.dataSource = []
        this.bussStorageNoticeMaterialTable.dataSource = []
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.bussStorageNoticeCarinfo.list, params, this.bussStorageNoticeCarinfoTable)
          this.requestSubTableData(this.url.bussStorageNoticeMaterial.list, params, this.bussStorageNoticeMaterialTable)
          // this.loadOption()
        }else {
          this.getPfCode();
        }
        // this.loaded()
      },
      //校验所有一对一子表表单
      validateSubForm(allValues){
        if(allValues.tablesValue[0].tableData.length == 0){
          this.$message.error('请添加收货信息！')
          return false;
        }
          return new Promise((resolve,reject)=>{
            Promise.all([
            ]).then(() => {
              resolve(allValues)
            }).catch(e => {
              if (e.error === VALIDATE_FAILED) {
                // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
              } else {
                console.error(e)
              }
            })
          })
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let _this = this;
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          bussStorageNoticeMaterialList: _this.loadMaterialData(_this.processingData(allValues.tablesValue[0].tableData)),
          bussStorageNoticeCarinfoList: _this.processingData(allValues.tablesValue[1].tableData),
        }
      },
      processingData(data){
        let newJsonArray = data.map(item => {
          return { ...item, id: item.id && item.id.indexOf('row') >= 0 ? '' : item.id  };
        });
        return newJsonArray;
      },
      loadMaterialData(data){
        data.forEach(item => {
          let actualNum = 0;
          let originalNum = 0;
          this.bussStorageNoticeCarinfoTable.dataSource.forEach(car =>{
            if(car.rowNum === item.rowNum && item.materialId === car.materialId ){
              actualNum +=  car.actualNum
              originalNum += car.originalNum
            }
          })
          item.actualNum = actualNum
          item.originalNum = originalNum
        })
        return data;
      },
      validateError(msg){
        this.$message.error(msg)
      },
      updateNoticeMaterial(rowNum,field,fieldval){
        this.bussStorageNoticeMaterialTable.dataSource.forEach(item => {
            if(item.rowNum == rowNum){
              item[field] = fieldval
            }
        })
      },
      scrollTop(){
        // 数据变动会出现滚动条无法滚动的情况，调用这个
        this.NoticeMaterialTable.resetScrollTop();
      },
      getRowNum(){
        let source = this.bussStorageNoticeMaterialTable.dataSource
        if(source.length === 0){
          return '0001'
        }
        let { rowNum } = source[source.length-1]
        let nextRowNum = Number(rowNum) + 1;
        if(nextRowNum < 10){
          return '000'+ nextRowNum;
        }else if(nextRowNum < 100){
          return '00'+ nextRowNum;
        }else if(nextRowNum < 1000){
          return '0'+ nextRowNum;
        }else {
          return String(nextRowNum)
        }
      }
    }
  }
</script>

<style scoped>
</style>
<style>
/*.vxe-table--body tr td{*/
/*  border: 1px solid #666666; !* 最下面的边框颜色 *!*/
/*}*/

/*.vxe-table--header thead tr th{*/
/*  border: 1px solid #666666; !* 最下面的边框颜色 *!*/
/*}*/

/*.vxe-table--header .vxe-header--row th{*/
/*  border-top: 1px solid #666666; !* 最下面的边框颜色 *!*/
/*}*/

/*.vxe-header--row th{*/
/*  border-left: 2px solid #666666;*/
/*  border-top: 2px solid #666666;*/
/*  border-bottom: 2px solid #666666;*/
/*}*/

/*.vxe-header--row th:last-child {*/
/*  border-right: 2px solid #666666;*/
/*}*/

/*.vxe-table--body .vxe-body--row td{*/
/*  border-left: 2px solid #666666;*/
/*  border-bottom: 2px solid #666666;*/
/*}*/

/*.vxe-table--body .vxe-body--row td:last-child {*/
/*  border-right: 2px solid #666666;*/
/*}*/


/*.ant-table-tbody tr:last-child tr td {*/
/*  border-bottom: 1px solid #666666; !* 最下面的边框颜色 *!*/
/*}*/

/*.ant-table-tbody  td {*/
/*  border: 1px solid #666666; !* 深灰色边框 *!*/
/*}*/

/*.ant-table-tbody tr:last-child  td {*/
/*  border-bottom: 1px solid #666666; !* 最下面的边框颜色 *!*/
/*}*/



/*.vxe-table--body-wrapper .vxe-header--row td{*/
/*  border-bottom: 1px solid #666666; !* 最下面的边框颜色 *!*/
/*}*/
/*.bold-border .vxe-table--main-wrapper .vxe-table .vxe-body--row .vxe-body--column {*/
/*  border: 2px solid #ccc; !* 设置边框粗细和颜色 *!*/
/*}*/

/*.bold-border .vxe-table--main-wrapper .vxe-table .vxe-footer--column {*/
/*  border-top: 2px solid #ccc; !* 表尾也可以加粗 *!*/
/*}*/

/*.bold-border table, tr, td {*/
/*  border: 1px solid black; !* 黑色边框，1px宽度 *!*/
/*}*/
/*.bold-border table, th, td {*/
/*  border: 1px solid black; !* 黑色边框，1px宽度 *!*/
/*}*/
/*.ant-card-body{*/
/*  padding: 10px 24px;*/
/*}*/
/*.ant-form-item {*/
/*  margin-bottom: 10px;*/
/*}*/
</style>